package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"time"
	
	"ebbflow/src/consensus"
)

func main() {
	// Parse command line arguments
	nodeID := flag.Int("id", 0, "Node ID")
	totalNodes := flag.Int("n", 4, "Total number of nodes")
	faultyNodes := flag.Int("f", 1, "Number of faulty nodes")
	epochs := flag.Int("epochs", 10, "Number of epochs to run")
	reconfigInterval := flag.Int("r", 5, "Reconfiguration interval (execute CBR every R epochs)")
	
	flag.Parse()
	
	// Setup logger
	logger := log.New(os.Stdout, fmt.Sprintf("[Node %d] ", *nodeID), log.LstdFlags)
	
	logger.Printf("=== CBR 协议测试 ===")
	logger.Printf("配置: N=%d, F=%d, 轮次数=%d, R=%d", *totalNodes, *faultyNodes, *epochs, *reconfigInterval)
	logger.Printf("")
	
	// Create CBR instance
	cbrNode := consensus.NewEbbFlowCBR(*nodeID, *totalNodes, *faultyNodes, logger)
	
	// Run CBR for multiple epochs
	logger.Printf("开始运行 CBR 协议...")
	logger.Printf("")
	
	for epoch := 0; epoch < *epochs; epoch++ {
		logger.Printf("--- 轮次 %d ---", epoch)
		
		// Check if CBR should execute at this epoch
		if cbrNode.ShouldExecute(epoch) {
			logger.Printf("✓ 在轮次 %d 执行 CBR 重配置", epoch)
			
			// Generate new membership (in real scenario, this would come from consensus)
			newMembership := generateMembership(*totalNodes)
			
			startTime := time.Now()
			result, err := cbrNode.ExecuteReconfiguration(epoch, newMembership)
			duration := time.Since(startTime)
			
			if err != nil {
				logger.Printf("✗ CBR 执行失败: %v", err)
			} else {
				logger.Printf("✓ CBR 执行成功，耗时: %v", result.Duration)
				logger.Printf("  新成员列表: %v", result.NewMembership)
				if len(result.ProactivizeKey) > 0 {
					logger.Printf("  密钥激活完成，密钥长度: %d 字节", len(result.ProactivizeKey))
				}
			}
			logger.Printf("  实际耗时: %v", duration)
		} else {
			logger.Printf("  跳过 CBR (非重配置轮次)")
		}
		logger.Printf("")
		time.Sleep(100 * time.Millisecond) // 模拟轮次间隔
	}
	
	// Print final metrics
	metrics := cbrNode.GetMetrics()
	logger.Printf("=== CBR 性能指标 ===")
	logger.Printf("总执行次数: %d", metrics.TotalExecutions)
	logger.Printf("成功次数: %d", metrics.SuccessfulExecutions)
	logger.Printf("失败次数: %d", metrics.FailedExecutions)
	if metrics.TotalExecutions > 0 {
		logger.Printf("平均耗时: %v", metrics.AverageDuration)
	}
	logger.Printf("最后执行时间: %v", metrics.LastExecution)
	logger.Printf("")
	logger.Printf("=== CBR 协议测试完成 ===")
}

func generateMembership(totalNodes int) []string {
	membership := make([]string, totalNodes)
	for i := 0; i < totalNodes; i++ {
		membership[i] = fmt.Sprintf("127.0.0.1:%d", 8000+i)
	}
	return membership
}

